package org.opens.javaskill.design;

import java.util.Arrays;

/**
 * 功能:
 * <p>简易版迭代器协议的实现</p>
 */
public class IteratorPattern {

    public static void main(String[] args) {
        MyList<String> list = new MyList<>(6);
        list.add("s1");
        list.add("s2");
        list.add("s3");
        System.out.println(list);
        MyIterator<String> iterator = list.getIterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

}

interface MyIterator<T> {

    public boolean hasNext();

    public T next();

}

interface MyContainer<T> {

    public MyIterator<T> getIterator();

}

class MyList<T> implements MyContainer<T> {

    private Object[] arr;

    private int size;

    private static final int DEFAULT_SIZE = 10;

    public MyList() {
        this.arr = new Object[DEFAULT_SIZE];
    }

    public MyList(int size) {
        this.arr = new Object[size];
    }

    public void add(T value) {
        int i = 0;
        while ( i < arr.length ) {
            if ( arr[i] == null ) {
                arr[i] = value;
                break;
            }
            i++;
        }
    }

    @Override
    public MyIterator<T> getIterator() {
        return new NameIterator<T>();
    }

    @Override
    public String toString() {
        return "MyList{" +
                "arr=" + Arrays.toString(arr) +
                '}';
    }

    private class NameIterator<T> implements MyIterator<T> {

        private int index;

        @Override
        public boolean hasNext() {
            return index < arr.length;
        }

        @Override
        public T next() {
            if ( hasNext() ) {
                return (T) arr[index++];
            }
            return null;
        }
    }

}